package com.shenmazong.serverwebpoem.shiro;

import com.shenmazong.serverwebpoem.pojo.TbUser;
import com.shenmazong.serverwebpoem.service.TbUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author 田不平
 * @project server-web-poem
 * @date 2020/3/24 9:05 PM
 * http://www.shenmazong.com
 */

@Slf4j
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    TbUserService tbUserService;

    /**
     * 1、用户验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("doGetAuthenticationInfo,执行用户认证");

        //--1 判断用户名是否存在
        UsernamePasswordToken userinfo = (UsernamePasswordToken) token;
        log.info("doGetAuthenticationInfo,username={}", userinfo.getUsername());
        TbUser user = tbUserService.getUserByName(userinfo.getUsername());
        if(null == userinfo) {
            log.info("doGetAuthenticationInfo,不存在用户:{}", userinfo.getUsername());
            return null;
        }

        //--2 判断密码
        log.info("doGetAuthenticationInfo,判断密码:{}", user.getUserpass());
        return new SimpleAuthenticationInfo(user, user.getUserpass(), user.getUsername());
    }

    /**
     * 2、用户授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("AuthorizationInfo,执行用户授权");

        //--1 获取用户信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();

        //--2 获取用户权限
//        List<String> perms = tbUserService.getPermissionsById(user.getId());
//        if(perms == null) {
//            return info;
//        }

        //--3 添加权限
//        info.addStringPermissions(perms);
//
//        return info;
        return null;
    }
}
